package com.hjm.common.utils.trade;


import com.alibaba.fastjson.JSON;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.util.Map;
import java.util.Random;

public class LoFunction {

	private final String defultCode = "UTF-8";

	static  LoFunction loFunction=new LoFunction();

	public static LoFunction getInstans(){
		return loFunction;
	}

	public String changeMoneyToFen(String amount) throws Exception {
		NumberFormat format = NumberFormat.getInstance();
		Number number = format.parse(amount);
		double temp = number.doubleValue() * 100.0;
		// 默认情况下GroupingUsed属性为true 不设置为false时,输出结果为2,012
		format.setGroupingUsed(false);
		// 设置返回数的小数部分所允许的最大位数
		format.setMaximumFractionDigits(0);
		return format.format(temp);
	}

	public BigDecimal changeMoneyToYuan(String amount) {
		return new BigDecimal(amount).setScale(2, BigDecimal.ROUND_DOWN)
				.divide(new BigDecimal(100));
	}

	public String hexStr2Str(String hexStr) {
	    String str = "0123456789ABCDEF";
	    char[] hexs = hexStr.toCharArray();
	    byte[] bytes = new byte[hexStr.length() / 2];
	    int n;
	    for (int i = 0; i < bytes.length; i++) {
	        n = str.indexOf(hexs[2 * i]) * 16;
	        n += str.indexOf(hexs[2 * i + 1]);
	        bytes[i] = (byte) (n & 0xff);
	    }
	    return new String(bytes);
	}

	public boolean compireMoney(String money) throws Exception {
		int minMoney = 100;
		int maxMoney = 30000;
		int nowMoney = Integer.parseInt(money);
		return minMoney <= nowMoney ? maxMoney >= nowMoney : false;
	}

	public String convertCard(String cardNo) throws Exception {
		return DateUtil.appendField(cardNo.substring(0, 6), "****",
				cardNo.substring(cardNo.length() - 4));
	}

	public boolean checkArrays(String[] array, String str) throws Exception {
		for (String mt : array) {
			if (mt.equals(str)) {
				return true;
			}
		}
		return false;
	}

	public BigDecimal convertMoney(String money) throws Exception {
		String moneyStr1 = money.substring(0, money.length() - 2);
		String moneyStr2 = money.substring(money.length() - 2);
		String moneyStr = DateUtil.appendField(moneyStr1, ".", moneyStr2);
		return new BigDecimal(moneyStr).setScale(2, BigDecimal.ROUND_DOWN);
	}


	public String convertMoney1(String money) throws Exception {
		String totalMoney = money.substring(0, money.length()).replace(".", "");
		StringBuffer zero = new StringBuffer();
		for (int i = 0; i < 12 - totalMoney.length(); i++) {
			zero.append("0");
		}
		totalMoney = zero.append(totalMoney).toString();
		return totalMoney;
	}

	public String changeMoney(String money) throws Exception {
		if (money.length() != 12) {
			StringBuffer x = new StringBuffer();
			for (int i = 0; i < 12 - money.length(); i++) {
				x.append("0");
			}
			return (x.append(money).toString());
		}
		return money;
	}

	public byte[] assemble(byte[]... b) throws Exception {
		int length = 0;
		for (byte[] bl : b) {
			if (bl != null){
				length += bl.length;
			}
		}
		byte[] data = new byte[length];
		int count = 0;
		for (int i = 0; i < b.length; i++) {
			if (b[i] != null) {
				System.arraycopy(b[i], 0, data, count, b[i].length);
				count += b[i].length;
			}
		}
		return data;
	}

	public int convertChar(int s) {
		return (s % 2 == 0) ? s / 2 : (s + 1) / 2;
	}

	public byte[] shortToBytes(short val) {
		byte[] b = new byte[2];
		for (int i = 0; i < 2; i++) {
			b[i] = (byte) (val >>> (8 - i * 8));
		}
		return b;
	}


	public boolean[] getBinaryFromByte(byte[] b) throws Exception {
		boolean[] binary = new boolean[b.length * 8 + 1];
		StringBuffer strsum = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			strsum.append(getEigthBitsStringFromByte(b[i]));
		}
		for (int i = 0; i < strsum.length(); i++) {
			binary[i + 1] = ("1".equalsIgnoreCase(strsum.substring(i, i + 1))) ? true
					: false;
		}
		return binary;
	}

	private String getEigthBitsStringFromByte(int b) throws Exception {
		b |= 256; // mark the 9th digit as 1 to make sure the string
		String str = Integer.toBinaryString(b);
		int len = str.length();
		return str.substring(len - 8, len);
	}

	public byte[] getByteFromBinary(boolean[] binary) throws Exception {
		int num = (binary.length - 1) / 8;
		num = ((binary.length - 1) % 8 != 0) ? num + 1 : num;
		byte[] b = new byte[num];
		StringBuffer s = new StringBuffer();
		for (int i = 1; i < binary.length; i++) {
			s.append((binary[i]) ? "1" : "0");
		}
		String tmpstr;
		int j = 0;
		for (int i = 0; i < s.length(); i = i + 8) {
			tmpstr = s.substring(i, i + 8);
			b[j] = getByteFromEigthBitsString(tmpstr);
			j = j + 1;
		}
		return b;
	}

	private byte getByteFromEigthBitsString(String str) throws Exception {
		byte b;
		if ("1".equals(str.substring(0, 1))) {
			str = DateUtil.appendField("0", str.substring(1));
			b = Byte.valueOf(str, 2);
			b |= 128;
		} else {
			b = Byte.valueOf(str, 2);
		}
		return b;
	}

	public int byteArrayToShort(byte[] b) throws Exception {
		return (b[0] << 8) + (b[1] & 0xFF);
	}


	public String byte2HexStr(byte[] b) throws Exception {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			hs = DateUtil.appendField(hs,
					(stmp.length() == 1) ? DateUtil.appendField("0", stmp)
							: stmp);
		}
		return hs.toUpperCase();
	}


	public byte[] hexStr2Bytes(String src) throws Exception {
		int m = 0, n = 0;
		int l = src.length() / 2;
		byte[] ret = new byte[l];
		for (int i = 0; i < l; i++) {
			m = i * 2 + 1;
			n = m + 1;
			ret[i] = uniteBytes(src.substring(i * 2, m), src.substring(m, n));
		}
		return ret;
	}

	private byte uniteBytes(String src0, String src1) throws Exception {
		byte b0 = Byte.decode(DateUtil.appendField("0x", src0)).byteValue();
		b0 = (byte) (b0 << 4);
		byte b1 = Byte.decode(DateUtil.appendField("0x", src1)).byteValue();
		byte ret = (byte) (b0 | b1);
		return ret;
	}

	public byte[] getAsciiBytes(String input) throws Exception {
		char[] c = input.toCharArray();
		byte[] b = new byte[c.length];
		for (int i = 0; i < c.length; i++) {
			b[i] = (byte) (c[i] & 0x007F);
		}
		return b;
	}

	public byte[] strToBCDBytes(String s) throws Exception {
		s = (s.length() % 2 != 0) ? DateUtil.appendField("0", s) : s;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		char[] cs = s.toCharArray();
		for (int i = 0; i < cs.length; i += 2) {
			int high = cs[i] - 48;
			int low = cs[i + 1] - 48;
			baos.write(high << 4 | low);
		}
		return baos.toByteArray();
	}

	public byte[] strToBCDBytesRight(String s) throws Exception {
		s = (s.length() % 2 != 0) ? DateUtil.appendField(s, "0") : s;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		char[] cs = s.toCharArray();
		for (int i = 0; i < cs.length; i += 2) {
			int high = cs[i] - 48;
			int low = cs[i + 1] - 48;
			baos.write(high << 4 | low);
		}
		return baos.toByteArray();
	}


	public int bcdToint(byte[] b) throws Exception {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			int h = ((b[i] & 0xff) >> 4) + 48;
			sb.append((char) h);
			int l = (b[i] & 0x0f) + 48;
			sb.append((char) l);
		}
		return Integer.parseInt(sb.toString());
	}

	public String bcdTostr(byte[] b) throws Exception {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			int h = ((b[i] & 0xff) >> 4) + 48;
			sb.append((char) h);
			int l = (b[i] & 0x0f) + 48;
			sb.append((char) l);
		}
		return sb.toString();
	}

	public String asciiToString(byte[] value) throws Exception {
		return new String(value, "GBK");
	}

	public byte[] asciiToByte(byte[] value) throws Exception {
		return hexStr2Bytes(new String(value, "GBK"));
	}

	public String initSize(int i) throws Exception {
		String j = DateUtil.appendField("0000", Integer.toString(i));
		return j.substring(j.length() - 4, j.length());
	}

	public String initSize(String i) throws Exception {
		String j = DateUtil.appendField("0000", i);
		return j.substring(j.length() - 4, j.length());
	}

	public String leftZero(String s) throws Exception {
		s = DateUtil.appendField("00000000000", s);
		return s.substring(s.length() - 11, s.length());
	}

	public String leftZero(String s, int i) throws Exception {
		s = DateUtil.appendField("000", s);
		return s.substring(s.length() - i, s.length());
	}

	public String rightZero(String s) throws Exception {
		return (s.length() % 2 != 0) ? DateUtil.appendField(s, "0") : s;
	}

	public String rightSpace(String s) {
		s = DateUtil.appendField(s, "                                        ");
		return s.substring(0, 40);
	}

	public boolean checkByte(byte[] byteData) throws Exception {
		return ("0000".equals(byte2HexStr(byteData))) ? true : false;
	}


	public String str2HexStr(String str) throws UnsupportedEncodingException {
		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes("GBK");
		int bit;
		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
		}
		return sb.toString();
	}

	public String byteArr2HexStr(byte[] arrB) throws Exception {
		int iLen = arrB.length;
		StringBuffer sb = new StringBuffer(iLen * 2);
		for (int i = 0; i < iLen; i++) {
			int intTmp = arrB[i];
			while (intTmp < 0) {
				intTmp = intTmp + 256;
			}
			if (intTmp < 16) {
				sb.append("0");
			}
			sb.append(Integer.toString(intTmp, 16));
		}
		return sb.toString();
	}

	public byte[] hexStr2ByteArr(String strIn) throws Exception {
		byte[] arrB = strIn.getBytes();
		int iLen = arrB.length;
		byte[] arrOut = new byte[iLen / 2];
		for (int i = 0; i < iLen; i = i + 2) {
			String strTmp = new String(arrB, i, 2);
			arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
		}
		return arrOut;
	}

	public String getSix() {
		String result = Integer.toString(new Random().nextInt(1000000));
		return (result.length() != 6) ? getSix() : result;
	}

	public byte[] mapToByte(Map<String, String> dataMap) throws Exception {
		String str = JSON.toJSONString(dataMap);
		byte[] by = str.getBytes(defultCode);
		String len = "0000" + by.length;
		len = len.substring(len.length() - 4);
		byte[] lenlen = len.getBytes(defultCode);
		byte[] pack = new byte[4 + by.length];
		System.arraycopy(lenlen, 0, pack, 0, 4);
		System.arraycopy(by, 0, pack, 4, by.length);
		return pack;
	}

	/**
	 *********************************************************.<br>
	 * [方法] MD5 <br>
	 * [描述] MD5加密方法 <br>
	 * [参数] 加密字符串 <br>
	 * [返回] String <br>
	 * [时间] 2018年11月21日 下午3:10:14 <br>
	 *********************************************************.<br>
	 */
	public String MD5(String str){
		char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		try {
			byte[] itInput=str.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest md=MessageDigest.getInstance("MD5");
			//使用指定的字节更新摘要
			md.update(itInput);
			//获取密文
			byte[] mdMd5=md.digest();
			//把密文转换成十六进制的字符串形式
			int j=mdMd5.length;
			char[] chr=new char[j*2];
			int k=0;
			for (int i = 0; i < j; i++) {
				byte bt=mdMd5[i];
				chr[k++] = hexDigits[bt >>> 4 & 0xf];
				chr[k++] = hexDigits[bt & 0xf];
			}
			return new String(chr);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
